﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Common.Tools;
using Domain;
using Domain.Entity;
using mshtml;
using Spider.Service;

namespace Spider.Spiders.Workers
{
    internal partial class QqWBSprider
    {
        protected override string GetFinalUrl(string sourceContent, PageDataSource dataSource)
        {
            switch (dataSource)
            {
                default:
                    return sourceContent;
            }
        }
        /// <summary>
        /// 登录QQ微博
        /// </summary>
        /// <returns></returns>
        private QQAcount DealLoginQQWb()
        {
            var qqAcounts = SpiderService.GetEnabledQqAcountsForWb().OrderBy(x => x.LastLoginForWB);
            var acount = qqAcounts.FirstOrDefault(x => x.MaxVisiteTimesForWB > x.VisitedTimesForWB && x.IsLoginForWB);
            if (acount == null)
            {
                acount = qqAcounts.FirstOrDefault(x => x.MaxVisiteTimesForWB > x.VisitedTimesForWB && !x.IsLoginForWB);
                if (acount == null)
                    throw new Exception("账号已经使用完了");
            }
            //判断是否登录
            else if (Spider.WebBrowser.Document != null && Spider.WebBrowser.Document.Cookie.Contains("skey="))
            {
                var content = Spider.WebBrowser.DocumentText;
                if (!content.Contains("登录"))
                    return acount;
            }
            Spider.WebBrowser.Document.Cookie.Remove(0, (Spider.WebBrowser.Document.Cookie.Count() - 1));
            var loginout = Spider.WebBrowser.Document.GetElementById("logout");
            if (loginout == null)
            {
                Spider.WebBrowser.Navigate("http://t.qq.com/");
                SpiderHelper.DelayTime(3);
                loginout = Spider.WebBrowser.Document.GetElementById("logout");
            }
            if (loginout != null)
            {
                loginout.InvokeMember("click");
                SpiderHelper.DelayTime(3);
            }
            Spider.WebBrowser.Navigate("http://t.qq.com/");
            while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            SpiderHelper.DelayTime(3);
            //获取网页文档对象，相当于获取网页的全部源码
            HtmlDocument htmlDoc = Spider.WebBrowser.Document;
            try
            {
                var temp = htmlDoc.Window.Frames["login_div"];
            }
            catch (Exception ex)
            {
                CustomsLog.WriteInfoLog("QQ账号登陆失败，登陆框未找到", ex.ToString());
                return DealLoginQQWb();
            }
            var login_frame = htmlDoc.Window.Frames["login_div"];
            IHTMLDocument3 loginframe = CorssDomainHelper.GetDocumentFromWindow(login_frame.DomWindow as IHTMLWindow2);
            //切换到设置QQ号码
            var switcher_plogin = loginframe.getElementById("switcher_plogin");
            switcher_plogin.click();
            SpiderHelper.DelayTime(2);
            //取消自动登录
            var p_low_login_enable = loginframe.getElementById("p_low_login_enable");
            if (p_low_login_enable.outerHTML.Contains("checked"))
                p_low_login_enable.click();
            //设置QQ号码
            var qqNum = loginframe.getElementById("u");
            qqNum.setAttribute("value", acount.QQ);
            //出发提前通知服务器更换账号登陆
            IHTMLDocument2 vDocument0 = loginframe as IHTMLDocument2;
            if (vDocument0 != null)
            {
                vDocument0.parentWindow.execScript(
                    "window.document.getElementById('u').focus();window.document.getElementById('p').focus();");
                SpiderHelper.DelayTime(3);
            }
            //设置QQ密码
            var qqPass = loginframe.getElementById("p");
            qqPass.setAttribute("value", acount.Pass);

            //登录
            var btnLogin = loginframe.getElementById("login_button");
            btnLogin.click();
            while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            SpiderHelper.DelayTime(5);
            RetryLogin(btnLogin, loginframe);
            SpiderService.SetQQWbLoginState(acount.QQ);
            Workers.QqWBSprider._hasvisitedDestinationUrl = false;
            _currentAcountVerifyCodeErrorTimes = Workers.QqWBSprider.AutoWritVerifyCodeErrorTimes > 0 ? Workers.QqWBSprider.AutoWritVerifyCodeErrorTimes : 1;
            return acount;
        }
        /// <summary>
        /// 登录QQ微博通过空间方式
        /// </summary>
        /// <returns></returns>
        private QQAcount DealLoginQQWbByZone()
        {
            var qqAcounts = SpiderService.GetEnabledQqAcountsForWb().OrderBy(x => x.LastLoginForWB);
            var acount = qqAcounts.FirstOrDefault(x => x.MaxVisiteTimesForWB > x.VisitedTimesForWB && x.IsLoginForWB);
            if (acount == null)
            {
                acount = qqAcounts.FirstOrDefault(x => x.MaxVisiteTimesForWB > x.VisitedTimesForWB && !x.IsLoginForWB);
                if (acount == null)
                    throw new Exception("账号已经使用完了");
            }
            //判断是否登录
            else if (Spider.WebBrowser.Document != null && Spider.WebBrowser.Document.Cookie.Contains("skey="))
            {
                var content = Spider.WebBrowser.DocumentText.Replace("QQ登录", "");//排除页尾登录字
                if (!content.Contains("登录"))
                    return acount;
            }
            Spider.WebBrowser.Document.Cookie.Remove(0, (Spider.WebBrowser.Document.Cookie.Count() - 1));
            var loginout = Spider.WebBrowser.Document.GetElementById("logout");
            if (loginout == null)
            {
                Spider.WebBrowser.Navigate("http://qzone.qq.com/");
                SpiderHelper.DelayTime(3);
                loginout = Spider.WebBrowser.Document.GetElementById("logout");
            }
            if (loginout != null)
            {
                loginout.InvokeMember("click");
                SpiderHelper.DelayTime(3);
            }
            Spider.WebBrowser.Navigate("http://qzone.qq.com/");
            while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            SpiderHelper.DelayTime(3);
            //获取网页文档对象，相当于获取网页的全部源码
            HtmlDocument htmlDoc = Spider.WebBrowser.Document;
            try
            {
                var temp = htmlDoc.Window.Frames["login_frame"];
            }
            catch (Exception ex)
            {
                CustomsLog.WriteInfoLog("QQ账号登陆失败，登陆框未找到", ex.ToString());
                return DealLoginQQWbByZone();
            }
            var login_frame = htmlDoc.Window.Frames["login_frame"];
            IHTMLDocument3 loginframe = CorssDomainHelper.GetDocumentFromWindow(login_frame.DomWindow as IHTMLWindow2);
            //切换到设置QQ号码
            var switcher_plogin = loginframe.getElementById("switcher_plogin");
            switcher_plogin.click();
            SpiderHelper.DelayTime(2);
            //设置QQ号码
            var qqNum = loginframe.getElementById("u");
            qqNum.setAttribute("value", acount.QQ);
            //出发提前通知服务器更换账号登陆
            IHTMLDocument2 vDocument0 = loginframe as IHTMLDocument2;
            if (vDocument0 != null)
            {
                vDocument0.parentWindow.execScript(
                    "window.document.getElementById('u').focus();window.document.getElementById('p').focus();");
                SpiderHelper.DelayTime(3);
            }
            //设置QQ密码
            var qqPass = loginframe.getElementById("p");
            qqPass.setAttribute("value", acount.Pass);

            //登录Qzone
            var btnLogin = loginframe.getElementById("login_button");
            btnLogin.click();
            while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            SpiderHelper.DelayTime(5);
            RetryLogin(btnLogin, loginframe);
            SpiderService.SetQQWbLoginState(acount.QQ);
            Workers.QqWBSprider._hasvisitedDestinationUrl = false;
            _currentAcountVerifyCodeErrorTimes = Workers.QqWBSprider.AutoWritVerifyCodeErrorTimes > 0 ? Workers.QqWBSprider.AutoWritVerifyCodeErrorTimes : 1;
            return acount;
        }
        private void DealLoginQQZoneForPostAd(object obj)
        {
            string[] acount = obj.ToString().Split("&".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            var loginout = Spider.WebBrowser.Document.GetElementById("logout");
            if (loginout == null)
            {
                Spider.WebBrowser.Navigate("http://qzone.qq.com/");
                SpiderHelper.DelayTime(3);
                loginout = Spider.WebBrowser.Document.GetElementById("logout");
            }
            if (loginout != null)
            {
                loginout.InvokeMember("click");
                SpiderHelper.DelayTime(3);
            }
            Spider.WebBrowser.Navigate("http://qzone.qq.com/");
            while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            SpiderHelper.DelayTime(3);
            //获取网页文档对象，相当于获取网页的全部源码
            HtmlDocument htmlDoc = Spider.WebBrowser.Document;
            try
            {
                var temp = htmlDoc.Window.Frames["login_frame"];
            }
            catch (Exception ex)
            {
                CustomsLog.WriteInfoLog("QQ账号登陆失败，登陆框未找到", ex.ToString());
                DealLoginQQZoneForPostAd(obj);
            }
            var login_frame = htmlDoc.Window.Frames["login_frame"];
            IHTMLDocument3 loginframe = CorssDomainHelper.GetDocumentFromWindow(login_frame.DomWindow as IHTMLWindow2);
            //切换到设置QQ号码
            var switcher_plogin = loginframe.getElementById("switcher_plogin");
            switcher_plogin.click();
            SpiderHelper.DelayTime(2);
            //设置QQ号码
            var qqNum = loginframe.getElementById("u");
            qqNum.setAttribute("value", acount[0]);
            //出发提前通知服务器更换账号登陆
            IHTMLDocument2 vDocument0 = loginframe as IHTMLDocument2;
            if (vDocument0 != null)
            {
                vDocument0.parentWindow.execScript(
                    "window.document.getElementById('u').focus();window.document.getElementById('p').focus();");
                SpiderHelper.DelayTime(3);
            }
            //设置QQ密码
            var qqPass = loginframe.getElementById("p");
            qqPass.setAttribute("value", acount[1]);

            //登录Qzone
            var btnLogin = loginframe.getElementById("login_button");
            btnLogin.click();
            while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            SpiderHelper.DelayTime(5);
            RetryLogin(btnLogin, loginframe);
            //SpiderService.SetQQWbLoginState(acount.QQ);
            _currentAcountVerifyCodeErrorTimes = Workers.QqWBSprider.AutoWritVerifyCodeErrorTimes > 0 ? Workers.QqWBSprider.AutoWritVerifyCodeErrorTimes : 1;
           
        }
        /// <summary>
        /// 重复试探登录
        /// </summary>
        /// <param name="btnLogin"></param>
        /// <param name="loginframe"></param>
        /// <returns></returns>
        private bool RetryLogin(IHTMLElement btnLogin, IHTMLDocument3 loginframe)
        {
            //判断当前是否已经成功登录系统
            if (Spider.WebBrowser.DocumentText.Contains("留住感动"))
            {
                //设置验证码
                IHTMLElement verifyCode = loginframe.getElementById("verifyimg");
                if (verifyCode != null)
                {
                    var src = verifyCode.getAttribute("src");
                    if (!string.IsNullOrWhiteSpace(src))
                    {
                        AttachVerifyCode(verifyCode, loginframe);
                        while (string.IsNullOrWhiteSpace(Workers.QqWBSprider.VerifyCode))
                        {
                            Application.DoEvents();
                        }
                        var txtcode = loginframe.getElementById("verifycode");
                        txtcode.setAttribute("value", Workers.QqWBSprider.VerifyCode);
                        Workers.QqWBSprider.VerifyCode = null;
                    }

                }
                btnLogin.click();
                while (Spider.WebBrowser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }
                SpiderHelper.DelayTime(5);
                if (!Spider.WebBrowser.Document.Cookie.Contains("skey="))
                {
                    RetryLogin(btnLogin, loginframe);
                }
            }
            return true;
        }
        /// <summary>
        /// 更换验证码
        /// </summary>
        internal void ChangeVerifyCode()
        {
            //获取网页文档对象，相当于获取网页的全部源码
            HtmlDocument htmlDoc = Spider.WebBrowser.Document;
            var login_frame = htmlDoc.Window.Frames["login_frame"];
            IHTMLDocument3 loginframe = CorssDomainHelper.GetDocumentFromWindow(login_frame.DomWindow as IHTMLWindow2);
            var verifyimg = loginframe.getElementById("verifyimg");
            verifyimg.click();
            SpiderHelper.DelayTime(3);
            AttachVerifyCode(verifyimg, loginframe);
        }
        /// <summary>
        /// 拷贝验证码到内存
        /// </summary>
        /// <param name="verifyCode"></param>
        /// <param name="loginframe"></param>
        protected void AttachVerifyCode(IHTMLElement verifyCode, IHTMLDocument3 loginframe)
        {
            IHTMLImgElement img = verifyCode as IHTMLImgElement;
            HTMLDocument doc = loginframe as HTMLDocument;
            HTMLBody body = (HTMLBody)doc.body;
            IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();
            rang.add(img as IHTMLControlElement);
            rang.execCommand("Copy", false, null);  //拷贝到内存  
            Workers.QqWBSprider.VerifyCodeImage = Clipboard.GetImage();
            if (Workers.QqWBSprider.AutoWritVerifyCode && _currentAcountVerifyCodeErrorTimes > 0)
            {
                var ret = SpiderService.Uu_recognizeByCodeTypeAndBytes(UtilMethod.GetByteImage(Workers.QqWBSprider.VerifyCodeImage));
                Workers.QqWBSprider.VerifyCode = ret;
                _currentAcountVerifyCodeErrorTimes--;
            }
        }
        /// <summary>
        /// 拷贝验证码到内存
        /// </summary>
        /// <param name="verifyCode"></param>
        /// <param name="loginframe"></param>
        protected void AttachVerifyCodeWithCatchPic(IHTMLElement verifyCode, IHTMLDocument3 loginframe)
        {
            IHTMLDocument2 vDocument0 = loginframe as IHTMLDocument2;
            vDocument0.parentWindow.execScript(
                "var elet=window.document.getElementById('verifyimg');elet.style.position='fixed';elet.style.top='0px';");
            // verifyCode.setAttribute("style", "position: fixed; z-index: 9999; top: 0px; left: 0px");
            var b = new Bitmap(300, 300);
            //WebBrowser.Visible = false;
            SpiderHelper.DelayTime(10);
            Spider.WebBrowser.DrawToBitmap(b, new Rectangle(new Point(), new Size(300, 300)));

            Workers.QqWBSprider.VerifyCodeImage = b;
            if (Workers.QqWBSprider.VerifyCodeImage != null)
            {
                Workers.QqWBSprider.VerifyCodeImage.Save("C:\\aa.bmp");
                CustomsLog.WriteInfoLog("宽：" + Workers.QqWBSprider.VerifyCodeImage.Width.ToString(), "");
            }
            else
            {
                CustomsLog.WriteInfoLog("图片对象Null：", "");
            }

            if (Workers.QqWBSprider.AutoWritVerifyCode && _currentAcountVerifyCodeErrorTimes > 0)
            {
                var ret = SpiderService.Uu_recognizeByCodeTypeAndBytes(UtilMethod.GetByteImage(Workers.QqWBSprider.VerifyCodeImage));
                Workers.QqWBSprider.VerifyCode = ret;
                _currentAcountVerifyCodeErrorTimes--;
            }
        }
        /// <summary>
        /// 加入搜索页搜索广播或用户
        /// </summary>
        /// <param name="destqq"></param>
        private void SearchBordercastOrUser(string destqq, string acount)
        {
            if (Spider.WebBrowser.Document == null) return;
            bool hasOpened = false;
            if (!Workers.QqWBSprider.EnableSearchUser)
                GetFinalHtmlByWebBrowser("http://search.t.qq.com/index.php?k=&pos=174&s_source=");
            else
                GetFinalHtmlByWebBrowser("http://search.t.qq.com/user.php?pos=436&k=");
            var txtsearch = Spider.WebBrowser.Document.GetElementById("k2");
            txtsearch.SetAttribute("value", destqq);
            var btnSearch = Spider.WebBrowser.Document.GetElementById("btn_top_search");
            btnSearch.InvokeMember("click");
            SpiderHelper.DelayTime(3);
            if (Spider.WebBrowser.DocumentText.Contains("搜太多啦"))
                throw new Exception("搜太多啦!");
            else if (Spider.WebBrowser.DocumentText.Contains("该QQ号码用户"))
            {
                hasOpened = true;
            }
            //记录是否当前QQ开通微博
            PageData pageData = new PageData();
            var btns = Spider.WebBrowser.Document.GetElementsByTagName("input");

            foreach (HtmlElement btn in btns)
            {
                if (btn.OuterHtml != null && btn.OuterHtml.Contains("立即收听") && btn.OuterHtml.Contains("left="))
                {
                    if (!Workers.QqWBSprider.EnableSearchUser)
                        hasOpened = true;
                    break;
                }
            }
            pageData.Data = acount + "&" + hasOpened.ToString();
            pageData.DataSource = PageDataSource.QQWbSearchPage;
            pageData.Date = DateTime.Now;
            pageData.PageUrl = destqq;
            PageRepository.AddPage(pageData);
        }
        /// <summary>
        /// 微博搜索页，点赞第一个
        /// </summary>
        /// <returns></returns>
        private void WbSayGood()
        {
            if (Spider.WebBrowser.Document == null) return;
            if (Workers.QqWBSprider.EnableSearchUser)
            {
                var elements0 = Spider.WebBrowser.Document.GetElementsByTagName("a");
                foreach (HtmlElement element in elements0)
                {
                    if (element.OuterHtml != null && element.OuterHtml.Contains("boss="))
                    {
                        element.InvokeMember("click");
                        break;
                    }
                }
                SpiderHelper.DelayTime(5);
            }
            var elements = Spider.WebBrowser.Document.GetElementsByTagName("i");
            foreach (HtmlElement element in elements)
            {
                if (element.OuterHtml != null && element.OuterHtml.Contains("ic ico_likeb"))
                {
                    element.InvokeMember("click");
                    break;
                }
            }
            SpiderHelper.DelayTime(5);
            if (!Spider.WebBrowser.Url.ToString().Contains("search.t.qq.com"))
            {
                var elements2 = Spider.WebBrowser.Document.GetElementsByTagName("i");
                foreach (HtmlElement element in elements2)
                {
                    if (element.OuterHtml != null && element.OuterHtml.Contains("ic ico_likeb"))
                    {
                        element.InvokeMember("click");
                        break;
                    }
                }
            }
            SpiderHelper.DelayTime(3);
        }
        /// <summary>
        /// 微博搜索页，加好友
        /// </summary>
        /// <returns></returns>
        private void WbAddFriend()
        {
            if (Spider.WebBrowser.Document == null) return;
            var btns = Spider.WebBrowser.Document.GetElementsByTagName("input");
            foreach (HtmlElement btn in btns)
            {
                if (btn.OuterHtml != null && btn.OuterHtml.Contains("立即收听") && btn.OuterHtml.Contains("left="))
                {
                    btn.InvokeMember("click");
                    break;
                }
            }
            SpiderHelper.DelayTime(2);
        }
        /// <summary>
        /// 微博发表
        /// </summary>
        /// <returns></returns>
        private void PostAd()
        {
            if (Spider.WebBrowser.Document == null) return;
            GetFinalHtmlByWebBrowser("http://t.qq.com/");
            var content = Spider.WebBrowser.Document.GetElementById("msgTxt");
            content.InnerText = "";
            var btns = Spider.WebBrowser.Document.GetElementsByTagName("input");
            foreach (HtmlElement btn in btns)
            {
                if (btn.OuterHtml != null && btn.OuterHtml.Contains("发送"))
                {
                    btn.InvokeMember("click");
                    break;
                }
            }
            SpiderHelper.DelayTime(2);
        }
    }
}
